<template>
  <div class="container" ref="mainCon">
    <div class="mainCon">
      <el-row
        class="searchBox searchInputWidth"
        style="padding-bottom: 0; position: relative"
      >
        <el-form :inline="true" :model="filterField">
          <el-col :lg="8" :xl="6">
            <el-form-item label="案件来源" class="row-padding-bottom">
              <el-input
                v-model="filterField.source"
                placeholder="请输入案件来源"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="接件处室" class="row-padding-bottom">
              <el-input
                v-model="filterField.ReceiveUnit"
                placeholder="请输入接件处室"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="接件日期">
                <timeSelection
                  :pickerOptions="pickerOptions1"
                  @getStartTimeValue="getbeginDateStart"
                  @getEndTimeValue="getbeginDateEnd"
                  :startTime="startTimeValueTwo"
                  :endTime="endTimeValueTwo"
                ></timeSelection>
              </el-form-item>
            </el-col>
            <!-- <el-col :lg="8" :xl="6">
                            <el-form-item label="所属行业" class="row-padding-bottom">
                                <el-input v-model="filterField.unit1" placeholder="请输入所属行业" clearable></el-input>
                            </el-form-item>
                        </el-col> -->
          </template>
          <!-- <el-col :lg="8" :xl="6" > -->
          <el-form-item class="btn">
            <!-- <el-button type="primary" icon="icon iconfont iconchazhao1" @click="searchList" class="commonBtn"></el-button> -->
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <div style="display: inline-block">
              <div class="uploadBox">
                <!-- <el-button round type="primary" class="createSalaryBut">导入</el-button> -->

                <el-button
                  type="primary"
                  class="createSalaryBut"
                  icon="icon iconfont icondaoru"
                  >导入</el-button
                >
                <div class="upLoadDom">
                  <form id="waterImportBox">
                    <input
                      type="file"
                      id="burstEventImportExcel"
                      name="file"
                      @change="burstEventImportfileChange"
                      title=""
                    />
                  </form>
                </div>
                <el-button
                  type="primary"
                  class="createSalaryBut"
                  icon="icon iconfont icondaochu"
                  @click="downLoadFile()"
                  >导出</el-button
                >
                <el-link
                  type="primary"
                  @click="burstEventDownLoad()"
                  class="uploadBtn"
                  >导入模板下载</el-link
                >
              </div>
            </div>
          </el-form-item>
          <!-- </el-col> -->
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <!-- 表格 -->
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          ref="tableBox1"
          @sort-change="sortChange"
          :max-height="tableHeight"
          @selection-change="handleSelectionChange"
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column label="案件来源" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.source"
                :columnName="'source'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column label="案情简要" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.caseBrief"
                :columnName="'caseBrief'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="petitionNum"
            sortable="custom"
            label="上访人数（人）"
            align="center"
            :formatter="formatTd"
            width="160"
          ></el-table-column>
          <el-table-column
            prop="receiveDate"
            sortable="custom"
            label="接件日期"
            align="center"
            :formatter="formatTd"
            width="140"
          ></el-table-column>
          <el-table-column
            prop="receiveUnit"
            label="接件处室"
            align="center"
            :formatter="formatTd"
            width="140"
          ></el-table-column>
          <el-table-column
            prop="caseState"
            label="办理情况"
            align="center"
            :formatter="formatTd"
            width="140"
          ></el-table-column>
          <!-- <el-table-column prop="statusDesc" label="所属行业" align="center" :formatter=formatTd width="180"></el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            :formatter="formatTd"
            width="160"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-link type="primary" @click="editData(scope.row.id)"
                >修改</el-link
              >
              <el-link type="primary" @click="deleteEvent(scope.row.id)"
                >删除</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
    </div>
    <el-dialog
      title="上传失败"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <div class="errorNoticeBox">
        <i class="icon iconfont iconshibai1"></i>
      </div>
      <div v-html="errorNotice" class="errorBox"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="closeDialog" class="save"
          >确认</el-button
        >
        <el-button @click.native="closeDialog" class="cancel">取消</el-button>
      </div>
    </el-dialog>
    <suddencase
      :id="itemId"
      @callback="handleDialog"
      :dialogTitle="dialogTitle"
      v-if="suddencaseDialog"
    />
  </div>
</template>
<script>
// import { mapState, mapActions } from "vuex";
import common from '../../kits/common'
import suddencase from './suddencase.vue'

export default {
  name: 'emergencies',
  components: {
    suddencase,
  },
  computed: {
    // ...mapState(["industryOptions"])
  },
  data() {
    return {
      //     pickerOptions1: {
      // 　　　　disabledDate (time){
      // 　　　　　　 return time.getTime() > Date.now();  //如果没有后面的-8.64e7就是不可以选择今天的
      // 　　　　}
      // 　　 },
      //搜索条件
      filterField: {
        source: '',
        ReceiveUnit: '',
        receiveStartDate: '',
        receiveEndDate: '',
      },
      isShow: false, //列表加载
      tableList: [],
      advanced: false,
      requestUrl: 'api-r/otherComplaint/emPage',
      administratorArr: [],
      loading: true,
      hiddleToolBar: false,
      tableHeight: null,
      formVisible: false,
      errorNotice: '',
      suddencaseDialog: false,
      dialogTitle: '修改',
      itemId: '',
    }
  },
  created() {
    // this.getAdministrator();
    // this.getIndustry({});
    if (this.$route.query.activeName) {
      this.filterField.ReceiveUnit = this.$route.query.ReceiveUnit
        ? this.$route.query.ReceiveUnit
        : ''
    }
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }
      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  methods: {
    // ...mapActions(["getIndustry"]),
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    getAdministrator() {
      this.axios({
        method: 'post',
        url: 'api-p/grid/expand/findgridusers',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.administratorArr = response.data.result
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    // 搜索
    searchList() {
      if (
        this.filterField.receiveStartDate &&
        this.filterField.receiveEndDate
      ) {
        if (
          this.filterField.receiveStartDate > this.filterField.receiveEndDate
        ) {
          this.$message({
            message: '开始日期不能大于结束日期',
            type: 'warning',
          })
          return
        }
      }
      this.$refs.pagination.getTableListData()
    },
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 230

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getbeginDateStart(val) {
      if (val) {
        this.filterField.receiveStartDate = val
        this.startTimeValueTwo = val
      } else {
        this.filterField.receiveStartDate = ''
        this.startTimeValueTwo = ''
      }
    },
    getbeginDateEnd(val) {
      if (val) {
        this.filterField.receiveEndDate = val
        this.endTimeValueTwo = val
      } else {
        this.filterField.receiveEndDate = ''
        this.endTimeValueTwo = ''
      }
    },
    // 导入模板下载
    burstEventDownLoad() {
      // window.location.href =
      // common.commonApi +
      // "api-r/complaint/registration/findurl?access_token=" +
      // localStorage.getItem("access_token");
      this.axios({
        method: 'post',
        url: 'api-r/complaint/registration/findurl',
        data: {
          type: '3',
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            window.open(response.data.result.url)
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 导入 ------start
    burstEventImportfileChange(e) {
      var that = this
      var url = window.location.href
      var Filedata = $('#burstEventImportExcel').val()
      var files = e.target.files[0]
      if (!/\.(xls|xlsx)$/.test(Filedata)) {
        this.$message({
          message: 'excel类型必须是.xls,xlsx中的一种',
          type: 'warning',
        })
        return
      }

      setTimeout(function () {
        that.uploadFileByAjaxSubmit(
          'api-r/otherComplaint/import',
          that.success,
          that.error
        )
      }, 500)
    },
    uploadFileByAjaxSubmit(url, successCallBack, errorCallBack) {
      const vm = this
      var token = localStorage.getItem('access_token')
      var options = {
        url: common.uploadUrl + url,
        type: 'POST',
        // data: vm.flieUpload,
        headers: { Authorization: 'Bearer ' + token },
        contentType: false,
        processData: false,
        success: function (data) {
          $('#burstEventImportExcel').val('')
          successCallBack(data)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $('#burstEventImportExcel').val('')
          errorCallBack(XMLHttpRequest, textStatus, errorThrown)
        },
      }

      //三种方式均可
      $('#waterImportBox').ajaxSubmit(options)
      return false
    },
    success(data) {
      if (!data.hasError) {
        this.$message({
          message: data.msg,
          type: 'success',
        })
        this.$nextTick(function () {
          this.$refs.pagination.getTableListData()
        })
      } else {
        this.errorNotice = data.errorMsg
        this.formVisible = true
      }
    },
    //根据状态码判断是否是401
    error(XMLHttpRequest, textStatus, errorThrown) {
      if (XMLHttpRequest.status === '401' || XMLHttpRequest.status === '403') {
        localStorage.setItem('access_token', '')
        localStorage.setItem('refresh_token', '')
        localStorage.setItem('userName', '')
        // 只有在当前路由不是登录页面才跳转
        if (router.currentRoute.path !== '/login/loginFirst') {
          router.replace({
            path: '/login/loginFirst',
          })
        }
        //清除tab栏数据
        this.$store.state.sliderBar = []
        localStorage.removeItem('sliderBar')
      } else {
        this.$message({
          message: '数据请求失败',
          type: 'warning',
        })
      }
    },
    closeDialog() {
      this.formVisible = false
    },
    // 删除
    deleteEvent(id) {
      this.$confirm('确定删除当前案件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.deleteRow(id)
        })
        .catch(() => {})
    },
    deleteRow(id) {
      this.axios({
        method: 'post',
        url: 'api-r/otherComplaint/delete',
        data: {
          id: id,
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {}
        )
        .catch((error) => {
          this.$message({
            message: '获取数据失败',
            type: 'error',
          })
        })
    },
    downLoadFile() {
      // window.open("http://devel.sunhj.cn:7004/statics/template/km/突发事件.xlsx")
      if (this.tableList.length > 0) {
        window.location.href =
          common.commonApi +
          'api-r/otherComplaint/export?source=' +
          this.filterField.source +
          '&ReceiveUnit=' +
          encodeURIComponent(this.filterField.ReceiveUnit) +
          '&receiveStartDate=' +
          this.filterField.receiveStartDate +
          '&receiveEndDate=' +
          this.filterField.receiveEndDate +
          '&sortField=' +
          this.filterField.sortField +
          '&sort=' +
          this.filterField.sort +
          '&access_token=' +
          localStorage.getItem('access_token')
      } else {
        this.$message({
          type: 'warning',
          message: '无数据导出',
        })
      }
    },
    editData(id) {
      this.itemId = id
      this.dialogTitle = '修改'
      this.suddencaseDialog = true
    },
    handleDialog(val) {
      this.suddencaseDialog = false
      if (val.success) {
        this.searchList()
      }
    },
  },
}
</script>
<style lang="less" scoped>
.uploadBox {
  position: relative;
  .upLoadDom {
    position: absolute;
    width: 96px;
    height: 36px;
    top: 0;
    left: 0;
    opacity: 0;
    line-height: 0px;
    form {
      input {
        width: 96px;
        height: 36px;
        line-height: 0px;
        cursor: pointer;
      }
    }
  }
}
.createSalaryBut {
  background: #009588;
  border: 1px solid #009588;
  padding: 10px 23px;
  margin-left: 12px;
  &:hover {
    opacity: 0.8;
  }
}
.errorNoticeBox {
  text-align: center;
  margin-bottom: 24px;
  i {
    color: red;
    font-size: 50px;
  }
}
.errorBox {
  line-height: 24px;
}
@import '../../../static/css/filterArea.less';
.btn {
  margin-right: 0;
}
</style>
